package tedu.cn.sp06.filter;

import cn.tedu.sp01.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


/*
模拟判断是否登陆
 */
@Component
public class LoginFilter extends ZuulFilter {
//过滤器的类型
    @Override
    public String filterType() {
        //return  "pre";
        return FilterConstants.PRE_TYPE;
    }
//设置过滤器的顺序号
    @Override
    public int filterOrder() {
        return 6;
    }
//判读针对当前请求，是否执行过滤代码
    @Override
    public boolean shouldFilter() {
        //调用商品检查权限
        //调用用户和订单不检查权限
        //获得一个请求上下文对象
        RequestContext ctx=RequestContext.getCurrentContext();
        //从上下文对象获取调用的服务id
        String serviceId=(String)ctx.get(FilterConstants.SERVICE_ID_KEY);

        return "item-service".equals(serviceId);
    }
//过滤代码
    @Override
    public Object run() throws ZuulException {
        //获取上下文对象
        RequestContext ctx=RequestContext.getCurrentContext();
        //获得request 对象
        HttpServletRequest request=ctx.getRequest();
        //接收 token 参数
        String token=request.getParameter("token");

        //如果没有token，阻止调用
        if(StringUtils.isBlank(token)){
            ctx.setSendZuulResponse(false);
           String json= JsonResult.err().code(JsonResult.NOT_LOGIN).msg("Not Login! 未登陆")
                    .toString();
           ctx.addZuulResponseHeader("Content-type", "application/json;charset=UTF-8");
           ctx.setResponseBody(json);


        }
        return null;
    }
}
